package cn.cj.erp.serviceimpl.system;

import cn.cj.erp.common.utils.Convert;
import cn.cj.erp.bo.system.SysRoleMenuBo;
import cn.cj.erp.service.system.SysRoleMenuService;
import cn.cj.erp.serviceimpl.base.ServiceImpl;
import cn.hutool.core.collection.CollectionUtil;
import cn.cj.erp.entity.system.SysRoleMenu;
import cn.cj.erp.dao.system.SysRoleMenuDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色与菜单对应关系
 *
 * @author chenjian
 */
@Slf4j
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenu, SysRoleMenuBo> implements SysRoleMenuService {
    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    public SysRoleMenuDao getBaseMapper() {
        return sysRoleMenuDao;
    }

    @Override
    public SysRoleMenu convert2Entity(SysRoleMenuBo sysRoleMenuBo) {
        return Convert.convert(sysRoleMenuBo, SysRoleMenu.class);
    }

    @Override
    public SysRoleMenuBo convert2Bo(SysRoleMenu sysRoleMenu) {
        return Convert.convert(sysRoleMenu, SysRoleMenuBo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAllMenusToRole(Long roleId, List<Long> menuIds) {
        //先删除角色与菜单关系
        boolean result = this.removeByRoleId(roleId);
        if (!result) {
            log.error("根据角色删除角色菜单表失败");
            // 批量保存失败，需要回滚
            rollback();
            return false;
        }
        if (CollectionUtil.isEmpty(menuIds)) {
            log.info("没有需要新增的数据，直接返回成功");
            return true;
        }
        //保存角色与菜单关系
        List<SysRoleMenuBo> list = SysRoleMenuBo.newList(roleId, menuIds);
        result = this.saveBatch(list);
        if (!result) {
            log.error("批量保存数据失败");
            // 批量保存失败，需要回滚
            rollback();
            return false;
        }
        return true;
    }

    @Override
    public List<Long> listMenuIdsByRoleId(Long roleId) {
        return getBaseMapper().listMenuIdsByRoleId(roleId);
    }

    @Override
    public int countByRoleId(Long roleId) {
        return lambdaQuery().eq(SysRoleMenu::getRoleId, roleId).count();
    }

    @Override
    public boolean removeByRoleId(Long roleId) {
        boolean needRemove = this.countByRoleId(roleId) > 0;
        if (!needRemove) {
            log.info("没有需要删除的数据，直接返回成功");
            return true;
        }
        return lambdaUpdate().eq(SysRoleMenu::getRoleId, roleId).remove();
    }

    @Override
    public boolean removeByRoleIds(List<Long> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            log.info("没有需要删除的数据，直接返回成功");
            return true;
        }
        return lambdaUpdate().in(SysRoleMenu::getRoleId, roleIds).remove();
    }


    public boolean existByMenuId(Long menuId) {
        return lambdaQuery().eq(SysRoleMenu::getMenuId, menuId).count() > 0;
    }
}
